<template>
  <div class="login">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="ruleForm">
      <h3>易购后台管理系统</h3>
      <el-form-item prop="username">
        <el-input v-model="ruleForm.username" placeholder="请输入用户名">
          <i slot="prefix" class="el-input__icon  el-icon-user"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="pwd">
        <el-input type="password" v-model="ruleForm.pwd" placeholder="请输入密码">
          <i slot="prefix" class="el-input__icon  el-icon-lock"></i>
        </el-input>
      </el-form-item>
      <el-form-item class="btn">
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import qs from 'qs'
export default {
  name: 'Login',
  data() {
    return {
      ruleForm: {
        username: 'admin',
        pwd: '123456a'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http({
          url: '/login',
          method: 'post',
          transformRequest: [
            function(data) {
              // 对 data 进行任意转换处理
              return qs.stringify(data)
            }
          ],
          data: this.ruleForm
        })
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: '登录失败，请重新登录！',
            type: 'error'
          })
        }
        this.$message({
          message: '恭喜你，登录成功！',
          type: 'success'
        })
        window.sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.login {
  width: 100%;
  height: 100%;
  background: rgb(131, 132, 197);
}
.ruleForm {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 400px;
  height: 320px;
  background: #f2f2f2;
  transform: translate(-50%, -50%);
  padding: 0 20px;
  box-sizing: border-box;
  border-radius: 5px;
  h3 {
    text-align: center;
    font-size: 22px;
    color: #808080;
    line-height: 60px;
  }
  .btn {
    text-align: right;
  }
}
</style>
